package com.braveman.im.ui.activity.message;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.braveman.im.R;
import com.braveman.im.bean.ChangeGroupAndComplate;
import com.braveman.im.bean.PicUpdateBean;
import com.braveman.im.manager.ApiManager;
import com.braveman.im.thread.CompressPhotoThread;
import com.braveman.im.ui.weiget.ButtonItem;
import com.braveman.im.ui.weiget.CustomPopwindow;
import com.braveman.im.ui.weiget.DialogUtils;
import com.braveman.im.utils.PermissionUtils;
import com.braveman.im.utils.UtilsStyle;
import com.bumptech.glide.Glide;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.ui.widget.TitleBarView;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.UIUtils;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.vondear.rxtools.RxBarTool;

import java.io.File;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;

public class EditCompanyInfoActivity extends BaseActivity {
    private QMUIRadiusImageView mIvActivityEditCompanyIcon;
    private ButtonItem mBtnActivityCompanyName;
    private ButtonItem mBtnActivityCompanyIntroduce;
    private ButtonItem mBtnActivityCompanyWelcome;
    private ButtonItem mBtiActivityCompanyJoinCondition;
    private ButtonItem mBtiActivityCompanyStates;
    private static final String TAKE_PHOTO_PATH = "ht/jkm/photo/COMPANY_ICON.jpg";
    private static final int REQUEST_CODE_TAKE_PHOTO = 1;
    private static final int REQUEST_CAMERA_CODE = 2;
    private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA = 0;
    private static final int MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD = 1;
    private static final int RESULE_CODE_FOR_NAME = 100;
    private static final int RESULE_CODE_FOR_INTRODUCE = 101;
    private static final int RESULE_CODE_FOR_WELCOME = 102;
    private String picturePath;
    private String groupId;


    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void initTitleBar() {
        mTitleBarView.setTitleText("编辑单位资料").setLeftBtnIcon(R.mipmap.back_black).setOnLeftBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityUtils.finishActivity(EditCompanyInfoActivity.this);
            }
        });
        mTitleBarView.addActions(new TitleBarView.Action("完成") {
            @Override
            public void performAction(View view) {
            }
        });
    }

    @Override
    protected int initContentView() {
        UtilsStyle.setStatusBarMode(this, true);
        RxBarTool.FlymeSetStatusBarLightMode(getWindow(), true);
        RxBarTool.MIUISetStatusBarLightMode(getWindow(), true);
        return R.layout.activity_edit_compand_info;
    }

    @Override
    protected void initIntentData(Intent callIntent) {
        groupId = callIntent.getStringExtra("groupId");
    }

    @Override
    protected void initChildView() {
        mIvActivityEditCompanyIcon = findViewById(R.id.iv_activity_edit_company_icon);
        mBtnActivityCompanyName = findViewById(R.id.btn_activity_company_name);
        mBtnActivityCompanyIntroduce = findViewById(R.id.btn_activity_company_introduce);
        mBtnActivityCompanyWelcome = findViewById(R.id.btn_activity_company_welcome);
        mBtiActivityCompanyJoinCondition = findViewById(R.id.bti_activity_company_join_condition);
        mBtiActivityCompanyStates = findViewById(R.id.bti_activity_company_states);

    }

    @Override
    protected void initChildData() {
        mIvActivityEditCompanyIcon.setCircle(true);
    }

    @Override
    protected void setChildViewListener() {
        mIvActivityEditCompanyIcon.setOnClickListener(this);
        mBtnActivityCompanyName.setOnClickListener(this);
        mBtnActivityCompanyIntroduce.setOnClickListener(this);
        mBtnActivityCompanyWelcome.setOnClickListener(this);
        mBtiActivityCompanyJoinCondition.setOnClickListener(this);
        mBtiActivityCompanyStates.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Bundle bundle = new Bundle();
        switch (v.getId()) {

            case R.id.iv_activity_edit_company_icon:
                try {
                    InputMethodManager im = (InputMethodManager) EditCompanyInfoActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                    im.hideSoftInputFromWindow(EditCompanyInfoActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (PermissionUtils.hasCameraPermission()) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture();
                    } else {
                        ActivityCompat.requestPermissions(EditCompanyInfoActivity.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    ActivityCompat.requestPermissions(EditCompanyInfoActivity.this,
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                }
                break;
            case R.id.btn_activity_company_name:
                bundle.putString("title", "单位名称");
                bundle.putString("groupId", groupId);
                bundle.putInt("type", 1);//修改单位名称
                ActivityUtils.startActivityForResult(this, ChangeCompanyInfoActivity.class, bundle, RESULE_CODE_FOR_NAME);
                break;
            case R.id.btn_activity_company_introduce:
                bundle.putString("title", "单位介绍");
                bundle.putString("groupId", groupId);
                bundle.putInt("type", 2);
                ActivityUtils.startActivityForResult(this, ChangeCompanyInfoActivity.class, bundle, RESULE_CODE_FOR_INTRODUCE);
                break;
            case R.id.btn_activity_company_welcome:
                bundle.putString("title", "欢迎语");
                bundle.putString("groupId", groupId);
                bundle.putInt("type", 3);
                ActivityUtils.startActivityForResult(this, ChangeCompanyInfoActivity.class, bundle, RESULE_CODE_FOR_INTRODUCE);
                break;
            case R.id.bti_activity_company_join_condition:
                WindowManager.LayoutParams lp = EditCompanyInfoActivity.this.getWindow()
                        .getAttributes();
                lp.alpha = 0.4f;
                EditCompanyInfoActivity.this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                EditCompanyInfoActivity.this.getWindow().setAttributes(lp);
                CustomPopwindow customPopwindow = DialogUtils.createPopwindow(this, "加入单位条件", "取消", new CustomPopwindow.OnBtnClickListener("允许任何人加单位") {
                    @Override
                    public void onClick(CustomPopwindow popwindow, View view) {
                        mBtiActivityCompanyJoinCondition.tv_title_del.setText("允许任何人加单位");
                    }
                }, new CustomPopwindow.OnBtnClickListener("只需要身份验证") {
                    @Override
                    public void onClick(CustomPopwindow popwindow, View view) {
                        mBtiActivityCompanyJoinCondition.tv_title_del.setText("只需要身份验证");
                    }
                }, new CustomPopwindow.OnBtnClickListener("只允许群成员邀请加单位") {
                    @Override
                    public void onClick(CustomPopwindow popwindow, View view) {
                        mBtiActivityCompanyJoinCondition.tv_title_del.setText("只允许群成员邀请加单位");
                    }
                }, new CustomPopwindow.OnBtnClickListener("不允许任何人加单位") {
                    @Override
                    public void onClick(CustomPopwindow popwindow, View view) {
                        mBtiActivityCompanyJoinCondition.tv_title_del.setText("不允许任何人加单位");
                    }
                }).setAutoDismiss(true);
                customPopwindow.showAtLocation(mBtiActivityCompanyJoinCondition, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 130);
                customPopwindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        WindowManager.LayoutParams lp = EditCompanyInfoActivity.this.getWindow()
                                .getAttributes();
                        lp.alpha = 1f;
                        EditCompanyInfoActivity.this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                        EditCompanyInfoActivity.this.getWindow().setAttributes(lp);

                    }
                });
                break;
        }
    }

    @Override
    protected void handleMessage(BaseActivity context, Message msg) {
        super.handleMessage(context, msg);
        switch (msg.what) {
            case 200: //图片
                int type = (int) msg.obj;
                String path = "";
                switch (type) {
                    case 0:
                        path = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                        Glide.with(EditCompanyInfoActivity.this)//
                                .load(path)//
                                .into(mIvActivityEditCompanyIcon);
                        toUpdata(path);
                        break;
                    case 1:
                        path = picturePath;
                        Glide.with(EditCompanyInfoActivity.this)//
                                .load(path)//
                                .into(mIvActivityEditCompanyIcon);
                        toUpdata(path);
                        break;
                }

                break;
        }
    }

    private void toUpdata(String path) {
        File file = new File(path);
        final RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        showLoadingDialog();
        ApiManager.getApi().uploadPic("image", filePart).enqueue(new NetCallBack<List<PicUpdateBean>>() {
            @Override
            protected void onSuccess(Call<List<PicUpdateBean>> call, Response<List<PicUpdateBean>> response) {
                UIUtils.showToast("图片上传成功");
                PicUpdateBean picUpdateBean = response.body().get(0);
                doNetWork(picUpdateBean.url, 1);
            }

            @Override
            protected void hiddenProgress() {
                hideLodingDialog();
            }
        });
    }

    private void doNetWork(String date, int type) {
        if (TextUtils.isEmpty(date)) {
            UIUtils.showToast("修改信息为空");
            return;
        }
        showLoadingDialog();
        ChangeGroupAndComplate changeGroupAndComplate = new ChangeGroupAndComplate();
        switch (type) {
            case 1:
                changeGroupAndComplate.icon = date;
                break;
        }
        ApiManager.getApi().changeComplateInfo(groupId, changeGroupAndComplate).enqueue(new NetCallBack<ChangeGroupAndComplate>() {
            @Override
            protected void onSuccess(Call<ChangeGroupAndComplate> call, Response<ChangeGroupAndComplate> response) {
                if (response != null) {
                    UIUtils.showToast("信息修改成功");
                }
            }

            @Override
            protected void hiddenProgress() {
                hideLodingDialog();
            }
        });
    }

    private void takePicture() {
        DialogUtils.createPopwindow(this, "", "取消", new CustomPopwindow.OnBtnClickListener("拍照") {
            @Override
            public void onClick(CustomPopwindow popwindow, View view) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = new File(Environment.getExternalStorageDirectory(), TAKE_PHOTO_PATH);
                Uri data;
                // 判断版本大于等于7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    // "net.csdn.blog.ruancoder.fileprovider"即是在清单文件中配置的authorities
                    data = FileProvider.getUriForFile(EditCompanyInfoActivity.this, "com.braveman.im.fileprovider", file);
                    // 给目标应用一个临时授权
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else {
                    data = Uri.fromFile(file);
                }
                intent.putExtra(MediaStore.EXTRA_OUTPUT, data);
                EditCompanyInfoActivity.this.startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);


            }
        }, new CustomPopwindow.OnBtnClickListener("从相册选择") {
            @Override
            public void onClick(CustomPopwindow popwindow, View view) {

                Intent i = new Intent(
                        Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, REQUEST_CAMERA_CODE);
            }
        }).showAtLocation(mTitleBarView, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 130);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_CALL_CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture();
                    } else {
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    Toast.makeText(this, "请打开拍照权限", Toast.LENGTH_SHORT).show();
                }
                break;
            case MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    takePicture();
                } else {
                    Toast.makeText(this, "请打开拍照权限", Toast.LENGTH_SHORT).show();
                }
                break;
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                case REQUEST_CODE_TAKE_PHOTO:
                    String filePath = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                    new CompressPhotoThread(mHandler, filePath, 0).start();
                    break;
                //                 选择照片
                case REQUEST_CAMERA_CODE:
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = this.getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    new CompressPhotoThread(mHandler, picturePath, 1).start();
                    break;
                case RESULE_CODE_FOR_NAME:
                    String change_name = data.getStringExtra("change_info");
                    mBtnActivityCompanyName.tv_title_del.setText(change_name);
                    break;
                case RESULE_CODE_FOR_INTRODUCE:
                    String change_introduce = data.getStringExtra("change_info");
                    mBtnActivityCompanyIntroduce.tv_title_del.setText(change_introduce);
                    break;
                case RESULE_CODE_FOR_WELCOME:
                    String change_welcome = data.getStringExtra("change_info");
                    mBtnActivityCompanyWelcome.tv_title_del.setText(change_welcome);
                    break;
            }
        }

    }

}
